<template>
  <a-drawer
    :title="formInfo.id == undefined ? '新增房间' : '修改房间'"
    :maskClosable="true"
    width="600"
    placement="right"
    :closable="true"
    @close="handleCancel"
    :destroyOnClose="true"
    :visible="visible"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model
        ref="ruleForm"
        :model="formInfo"
        :label-col="$global.labelCol"
        :wrapper-col="$global.wrapperCol"
      >
        <!-- <a-row>
          <a-col>
            <a-form-model-item
              label="所属院区"
              prop="campusAreaId"
              :rules="$valid.required"
              :maxLength="50"
            >
              <a-select
                :size="'default'"
                :showArrow="true"
                v-model="formInfo.campusAreaId"
                placeholder="请选择所属院区"
                @change="getCampusBuildingList(formInfo.campusAreaId)"
              >
                <a-select-option
                  v-for="item in campusAreaList"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.campusName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col>
            <a-form-model-item
              label="建筑物"
              prop="buildingId"
              :rules="$valid.required"
              :maxLength="50"
            >
              <a-select
                :size="'default'"
                :showArrow="true"
                v-model="formInfo.buildingId"
                placeholder="请选择建筑物"
                @change="getCampusBuildingFloorList(formInfo.buildingId)"
              >
                <a-select-option
                  v-for="item in campusBuildingList"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.buildingName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col>
            <a-form-model-item
              label="所属楼层"
              prop="floorId"
              :rules="$valid.required"
              :maxLength="50"
            >
              <a-select
                :size="'default'"
                :showArrow="true"
                v-model="formInfo.floorId"
                placeholder="请选择所属楼层"
              >
                <a-select-option
                  v-for="item in campusBuildingFloorList"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.floorName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row> -->
        <a-row>
          <a-col>
            <a-form-model-item
              label="房间名称"
              prop="roomName"
              :rules="$valid.required"
              :maxLength="50"
            >
              <a-input
                v-model="formInfo.roomName"
                placeholder="请输入房间名称"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col>
            <a-form-model-item
              label="房间编号"
              prop="roomNumber"
              :maxLength="50"
            >
              <a-input
                v-model="formInfo.roomNumber"
                placeholder="请输入房间编号"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col>
            <a-form-model-item
              label="房间类型"
              :rules="$valid.required"
              prop="roomType"
              :maxLength="50"
            >
              <a-radio-group
                v-model="formInfo.roomType"
                style="line-height: 35px"
              >
                <a-radio
                  v-for="item in this.$sysDictOptions('roomType')"
                  :key="item.k"
                  :value="item.k"
                  class="radio-item"
                  >{{ item.v }}</a-radio
                >
              </a-radio-group>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col>
            <a-form-model-item
              label="使用状态"
              :rules="$valid.required"
              prop="roomUseStatus"
              :maxLength="50"
            >
              <a-radio-group
                v-model="formInfo.roomUseStatus"
                style="line-height: 35px"
              >
                <a-radio
                  v-for="item in this.$sysDictOptions('roomUseStatus')"
                  :key="item.k"
                  :value="item.k"
                  class="radio-item"
                  >{{ item.v }}</a-radio
                >
              </a-radio-group>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col>
            <a-form-model-item
              label="专业分类"
              prop="professionalClassificationId"
              :maxLength="50"
            >
              <a-tree-select
                v-model:value="formInfo.professionalClassificationId"
                style="width: 100%"
                :tree-data="professionalClassificationIdTree"
                tree-checkable
                allow-clear
                placeholder="请选择专业分类"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col>
            <a-form-model-item
              label="使用科室"
              prop="departmentId"
              :maxLength="50"
            >
              <a-tree-select
                v-model="formInfo.departmentId"
                style="width: 100%"
                :tree-data="departmentTree"
                placeholder="请选择使用科室"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col>
            <a-form-model-item
              label="管理部门"
              prop="administrativeDept"
              :maxLength="50"
            >
              <a-select
                :size="'default'"
                style="min-width: 100px"
                :showArrow="true"
                v-model="formInfo.administrativeDept"
                placeholder="请选择管理部门"
              >
                <a-select-option
                  v-for="item in this.$sysDictOptions('administrativeDept')"
                  :key="item.k"
                  :value="item.k"
                >
                  {{ item.v }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col>
            <a-form-model-item
              label="使用面积"
              prop="usableArea"
              :maxLength="50"
            >
              <a-input
                type="number"
                v-model="formInfo.usableArea"
                placeholder="请输入使用面积"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col>
            <a-form-model-item
              label="房屋朝向"
              prop="roomOrientation"
              :maxLength="50"
            >
              <a-select
                :size="'default'"
                style="min-width: 100px"
                :showArrow="true"
                v-model="formInfo.roomOrientation"
                placeholder="请选择房屋朝向"
              >
                <a-select-option
                  v-for="item in this.$sysDictOptions('roomOrientation')"
                  :key="item.k"
                  :value="item.k"
                >
                  {{ item.v }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col>
            <a-form-model-item
              label="房间管理员"
              prop="roomAdmin"
              :maxLength="50"
            >
              <a-select
                :size="'default'"
                style="min-width: 100px"
                :showArrow="true"
                v-model="formInfo.roomAdmin"
                placeholder="请选择房间管理员"
              >
                <a-select-option
                  v-for="item in roomAdminList"
                  :key="item.companyId"
                  :value="item.companyId"
                >
                  {{ item.companyName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col>
            <a-form-model-item
              label="联系电话"
              prop="contactPhones"
              :maxLength="50"
            >
              <a-table
                :columns="contractOtherColumns"
                :dataSource="contractOtherList"
                :pagination="false"
                bordered
                size="middle"
                rowKey="key"
              >
                <!-- 自定义单元格渲染 - 可编辑单元格 v-for="(row, index) in data" -->
                <template
                  v-for="col in editableContractOtherColumns"
                  :slot="col.dataIndex"
                  slot-scope="text, record, index"
                >
                  <div :key="col.dataIndex" class="editable-cell">
                    <a-input v-model="record[col.dataIndex]" />

                    <div
                      class="error-message"
                      v-if="record.errors && record.errors[col.dataIndex]"
                    >
                      {{ record.errors[col.dataIndex] }}
                    </div>
                  </div>
                </template>

                <!-- 操作列 - 添加/删除行按钮 -->
                <template slot="action" slot-scope="text, record, index">
                  <div class="action-buttons">
                    <a-tooltip title="添加一行">
                      <a-button
                        type="primary"
                        shape="circle"
                        icon="plus"
                        size="small"
                        @click="addContractOtherRow(index)"
                        v-if="index === contractOtherList.length - 1"
                        :disabled="hasContractOtherErrors"
                      />
                    </a-tooltip>
                    <a-tooltip title="删除此行" v-if="index != 0">
                      <a-button
                        style="background-color: #d9d9d9"
                        type="default"
                        shape="circle"
                        icon="minus"
                        size="small"
                        @click="removeContractOtherRow(index)"
                        v-if="
                          contractOtherList.length > 1 &&
                          index === contractOtherList.length - 1
                        "
                      />
                    </a-tooltip>
                  </div>
                </template>
              </a-table>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row style="margin-top: 20px">
          <a-col>
            <a-form-model-item label="备注">
              <a-input v-model="formInfo.remarks" type="textarea" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row style="margin-top: 20px">
          <a-col>
            <a-form-model-item label="图片" prop="pictureImage" :maxLength="50">
              <w-image-upload
                class="avatar-uploader"
                text="上传"
                :multipleFlag="false"
                :file-max-size="1"
                v-model="formInfo.pictureImage"
                bizPath="companyPic"
              ></w-image-upload>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row style="margin-top: 20px">
          <a-col>
            <a-form-model-item label="附件" prop="enclosure" :maxLength="50">
              <w-file-upload
                class="avatar-uploader"
                text="上传"
                :pdfOnly="true"
                :multipleFlag="true"
                v-model="formInfo.enclosure"
                bizPath="annexUrl"
              >
              </w-file-upload>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-spin>
    <div
      style="
        display: flex;
        justify-content: flex-end; /* 将内容推到右侧 */
        align-items: flex-end; /* 将内容推到下方 */
        height: 100vh; /* 容器高度设为视口高度，确保它在屏幕底部 */
      "
    >
      <a-button @click="handleCancel" style="margin-right: 0.8rem"
        >取消</a-button
      >
      <a-button
        style="margin-right: 0.8rem"
        @click="handleSubmit"
        type="primary"
        :loading="confirmLoading"
        >保存</a-button
      >
    </div>
    <div style="height: 50px"></div>
  </a-drawer>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
import WImageUpload from '@/components/WxImageUpload/WImageUpload'
import WFileUpload from '@/components/WxFileUpload/WFileUpload.vue'
import { getDepartTree } from '@/api/api'
import { getCompanyList } from '@/api/api'
export default {
  name: 'DevCampusBuildingFloorRoomEdit',
  components: { WImageUpload, WFileUpload },
  data() {
    return {
      campusAreaList: [],
      campusBuildingList: [],
      campusBuildingFloorList: [],
      professionalClassificationIdTree: [],
      departmentTree: [],
      roomAdminList: [],
      contractOtherColumns: [
        {
          title: '电话号码',
          dataIndex: 'phone',
          scopedSlots: {
            customRender: 'phone',
          },
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '10%',
          scopedSlots: { customRender: 'action' },
        },
      ],
      contractOtherList: [
        {
          key: Date.now().toString(),
          phone: undefined,
          errors: {},
        },
      ],
      visible: false,
      confirmLoading: false,
      formInfo: {
        createTime: undefined,
        buildingId: undefined,
        campusAreaId: undefined,
        floorId: undefined,
        roomName: undefined,
        roomNumber: undefined,
        roomType: undefined,
        roomUseStatus: undefined,
        professionalClassificationId: undefined,
        departmentId: undefined,
        administrativeDept: undefined,
        usableArea: undefined,
        roomOrientation: undefined,
        roomAdmin: undefined,
        contactPhones: undefined,
        remarks: undefined,
        pictureImage: undefined,
        enclosure: undefined,
        wx: '',
      },
      drawerWidth: 800,
      url: {
        saveInfo: '/system/devCampusBuildingFloorRoom/save',
        getInfo: '/system/devCampusBuildingFloorRoom/info',
        getCampusAreaList: '/system/devCampusArea/getList',
        getCampusBuildingList: 'system/devCampusBuilding/getList',
        getCampusBuildingFloorList: 'system/devCampusBuildingFloor/getList',
        getprofessionalClassificationIdTree:
          '/system/devProfessionalClassification/tree',
      },
      queryParam: {},
    }
  },
  computed: {
    editableContractOtherColumns() {
      return this.contractOtherColumns.filter(
        (col) => col.dataIndex !== 'action'
      )
    },
    // 检查是否有错误
    hasContractOtherErrors() {
      return this.contractOtherList.some(
        (row) => row.errors && Object.keys(row.errors).length > 0
      )
    },
  },
  created() {
    // 专业分类
    this.getprofessionalClassificationIdTree()
    //使用科室
    this.getDepartmentTree()
    //房间管理员
    this.getUserList()
  },
  methods: {
    getUserList() {
      // 房间管理员
      var parameter = { pageNo: 1, pageSize: 1000000 }
      getCompanyList(Object.assign(parameter, this.queryParam)).then((res) => {
        this.roomAdminList = res.result.data.records
      })
    },
    //使用科室
    getDepartmentTree() {
      getDepartTree().then((res) => {
        this.departmentTree = res.result.data
      })
    },
    //专业分类
    getprofessionalClassificationIdTree(e) {
      getAction(this.url.getprofessionalClassificationIdTree, {}).then(
        (res) => {
          this.professionalClassificationIdTree = res.result.data
        }
      )
    },

    getCampusAreaList() {
      getAction(this.url.getCampusAreaList).then((res) => {
        this.campusAreaList = res.result.data
      })
    },
    getCampusBuildingList(campusAreaId) {
      getAction(this.url.getCampusBuildingList, {
        campusAreaId: campusAreaId,
      }).then((res) => {
        this.campusBuildingList = res.result.data
      })
    },
    getCampusBuildingFloorList(buildingId) {
      getAction(this.url.getCampusBuildingFloorList, {
        buildingId: buildingId,
      }).then((res) => {
        this.campusBuildingFloorList = res.result.data
      })
    },

    // START 联系人手机号
    addContractOtherRow(index) {
      if (this.hasContractOtherErrors) return
      var indexOf = index + 1
      console.log('indexOf+1>>', indexOf + 1)
      this.contractOtherList.splice(indexOf, 0, {
        key: Date.now().toString(),
        phone: '',
        errors: {},
      })
    },

    // 删除行
    removeContractOtherRow(index) {
      this.contractOtherList.splice(index, 1)
    },

    // 验证字段
    validateContractOtherField(record, field) {
      // 清除旧错误
      if (record.errors && record.errors[field]) {
        this.$delete(record.errors, field)
      }

      // 必填校验规则
      const requiredFields = ['fundsSource', 'sourceRatio', 'amount']
      if (requiredFields.includes(field) && !record[field]) {
        this.$set(
          record.errors,
          field,
          `${this.getContractOtherFieldTitle(field)}不能为空`
        )
      }
    },

    // 获取字段标题
    getContractOtherFieldTitle(field) {
      const column = this.contractOtherColumns.find(
        (col) => col.dataIndex === field
      )
      return column ? column.title : field
    },

    // END联系人手机号
    add(item) {
      this.edit()
      this.formInfo.roomType = '1'
      this.formInfo.roomUseStatus = '0'
      this.contractOtherList = [
        {
          key: Date.now().toString(),
          phone: '',
          errors: {},
        },
      ]

      this.formInfo.campusAreaId = item.campusAreaId
      this.formInfo.buildingId = item.buildingId
      this.formInfo.floorId = item.floorId
    },
    edit(record) {
      this.$objToOverride(this.formInfo, record)
      if (this.formInfo.id) {
        getAction(this.url.getInfo, { id: record.id }).then((res) => {
          this.$nextTick(() => {
            this.formInfo = res.result.data
            if (this.formInfo.contactPhones) {
              this.contractOtherList = JSON.parse(this.formInfo.contactPhones)
            }

            if (this.formInfo.professionalClassificationId) {
              this.formInfo.professionalClassificationId =
                this.formInfo.professionalClassificationId.split(',')
            }

            //this.getCampusBuildingList(this.formInfo.campusAreaId)

            //this.getCampusBuildingFloorList(this.formInfo.buildingId)
          })
        })
      }
      this.visible = true
    },
    // 确定
    handleSubmit() {
      // 触发表单验证
      this.confirmLoading = true
      this.$refs.ruleForm.validate((valid) => {
        console.log(valid)
        if (valid) {
          if (this.contractOtherList) {
            this.formInfo.contactPhones = JSON.stringify(this.contractOtherList)
          }
          if (this.formInfo.professionalClassificationId) {
            this.formInfo.professionalClassificationId =
              this.formInfo.professionalClassificationId + ''
          }

          postAction(this.url.saveInfo, this.formInfo)
            .then((res) => {
              this.$message.success(res.content)
              this.$emit('ok', this.formInfo)
              this.close()
            })
            .finally(() => {
              this.confirmLoading = false
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    // 关闭
    handleCancel() {
      this.close()
    },
    close() {
      this.$refs.ruleForm.resetFields()
      this.$objToReset(this.formInfo)
      this.$emit('close')
      this.visible = false
    },
    editorOk(val) {
      this.formInfo.content = val
    },
  },
}
</script>
